Friendly way to override `const`-overloaded member function?

Posted by xtofl on Stack Overflow See other posts from Stack Overflow or by xtofl
Published on 2010-03-13T18:58:02Z Indexed on 2010/03/13 19:15 UTC
Read the original article Hit count: 81

Filed under:
|
|
|

Given a base class

class A {
  int i;
public:
  int& f(){ return i;}
  const int& f() const { return i;}
};

And a sub class

class ConstA : private A {
public:
    const int& f() const { return A::f(); }
};

Is there a wrist-friendly way to access the ConstA::f method on a non-const variable?

ConstA ca;

int i = ca.f(); 
// compile error: int& A::f() is not accessible since A is privately inherited

int j = static_cast<const ConstA&>(ca).f(); 
// this works, but it hurts a little...

Or is it so ugly since hiding A::f generally is a bad idea, violating the Liskov Substitution Principle: any subclass of A must at least be capable of all A's functionality?

void set( A& a, int i ) { a.f() = i; }

class ConstA2 : public A {
private: int& f(){ return A::f(); }
};

ConstA2 ca2;
set( ca2, 1 );

(Note: this question popped up while thinking about this question)

© Stack Overflow or respective owner

Related posts about c++

Related posts about liskov